package com.xspace.android.xafcommon.db;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class BaseSql {
	protected BaseDBHelper db;
	protected ContentValues values;
	protected String where;
	protected String selection;
	protected String[] selectionArgs;
	protected String TB_DELETE = "DROP TABLE IF EXISTS ";

	protected BaseSql() {
	}

	protected BaseSql(BaseDBHelper db) {
		this.db = db;
	}

	public abstract void create(SQLiteDatabase db);

	public abstract void upgrade(SQLiteDatabase db);

	protected synchronized int saveOrUpdate(String tableName) {
		return db.insertOrUpdate(tableName, values, where);
	}

	protected synchronized int save(String tableName) {
		return db.insert(tableName, values);
	}

	protected synchronized int update(String tableName) {
		return db.update(tableName, values, where);
	}

	protected int replace(String tableName) {
		return db.replace(tableName, values, where);
	}

	protected int delete(String tableName) {
		return db.delete(tableName, selection, selectionArgs);
	}

	protected int total(String table) {
		int size = 0;
		Cursor cur = db.query(table, where);
		if (cur != null) {
			size = cur.getCount();
			cur.close();
		}
		db.close();
		return size;
	}

	protected static byte[] getBytesFromObject(Object record) {
		try {
			ByteArrayOutputStream bar = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bar);
			oos.writeObject(record);
			byte[] data = bar.toByteArray();
			oos.close();
			bar.close();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// return Object
	protected static Object getObjectFromBytes(byte[] data) {
		try {
			ByteArrayInputStream bar = new ByteArrayInputStream(data);
			ObjectInputStream ois = new ObjectInputStream(bar);
			Object obj = ois.readObject();
			ois.close();
			bar.close();
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
